package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.ragflow.RAGFlowClient;
import com.docmgmt.mvp.ragflow.dto.ChatAssistantDetailVO;
import com.docmgmt.mvp.ragflow.dto.CreateChatAssistantRequest;
import com.docmgmt.mvp.ragflow.dto.UpdateChatAssistantRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * RAGFlow Chat Assistant 管理 Controller
 * 
 * 提供 Chat Assistant 的 CRUD 接口
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/ragflow/chats")
@RequiredArgsConstructor
@Tag(name = "RAGFlow Chat Assistant 管理", description = "RAGFlow Chat Assistant 创建、更新、删除、查询接口")
public class RAGFlowChatController {

    private final RAGFlowClient ragFlowClient;

    /**
     * 创建 Chat Assistant
     *
     * POST /api/v1/ragflow/chats
     *
     * @param request 创建请求
     * @return Chat Assistant 详情
     */
    @PostMapping
    @PreAuthorize("hasAuthority('chat:create')")
    @Operation(summary = "创建 Chat Assistant", description = "创建新的 Chat Assistant（对话助手）")
    public Result<ChatAssistantDetailVO> createChatAssistant(
            @Valid @RequestBody CreateChatAssistantRequest request) {
        try {
            log.info("收到创建 Chat Assistant 请求: name={}", request.getName());
            ChatAssistantDetailVO chat = ragFlowClient.createChatAssistant(request);
            log.info("Chat Assistant 创建成功: id={}, name={}", chat.getId(), chat.getName());
            return Result.success(chat);
        } catch (Exception e) {
            log.error("创建 Chat Assistant 失败", e);
            return Result.error("创建 Chat Assistant 失败: " + e.getMessage());
        }
    }

    /**
     * 更新 Chat Assistant 配置
     *
     * PUT /api/v1/ragflow/chats/{chatId}
     *
     * @param chatId  Chat Assistant ID
     * @param request 更新请求
     * @return 更新后的 Chat Assistant 详情
     */
    @PutMapping("/{chatId}")
    @PreAuthorize("hasAuthority('chat:update')")
    @Operation(summary = "更新 Chat Assistant 配置", description = "更新 Chat Assistant 的名称、LLM、Prompt等配置")
    public Result<ChatAssistantDetailVO> updateChatAssistant(
            @PathVariable String chatId,
            @Valid @RequestBody UpdateChatAssistantRequest request) {
        try {
            log.info("收到更新 Chat Assistant 配置请求: chat_id={}", chatId);
            ChatAssistantDetailVO chat = ragFlowClient.updateChatAssistant(chatId, request);
            log.info("Chat Assistant 配置更新成功: chat_id={}", chatId);
            return Result.success(chat);
        } catch (Exception e) {
            log.error("更新 Chat Assistant 配置失败: chat_id={}", chatId, e);
            return Result.error("更新 Chat Assistant 配置失败: " + e.getMessage());
        }
    }

    /**
     * 删除 Chat Assistant
     *
     * DELETE /api/v1/ragflow/chats
     *
     * @param requestBody 请求体，包含ids数组
     * @return 删除结果
     */
    @DeleteMapping
    @PreAuthorize("hasAuthority('chat:delete')")
    @Operation(summary = "删除 Chat Assistant", description = "批量删除 Chat Assistant")
    public Result<Void> deleteChatAssistants(
            @Valid @RequestBody Map<String, List<String>> requestBody) {
        try {
            List<String> chatIds = requestBody.get("ids");
            
            if (chatIds == null || chatIds.isEmpty()) {
                return Result.error("Chat Assistant ID列表不能为空");
            }

            log.info("收到删除 Chat Assistant 请求: chat_ids={}", chatIds);
            ragFlowClient.deleteChatAssistants(chatIds);
            log.info("Chat Assistant 删除成功: count={}", chatIds.size());
            return Result.success("Chat Assistant 删除成功");
        } catch (Exception e) {
            log.error("删除 Chat Assistant 失败", e);
            return Result.error("删除 Chat Assistant 失败: " + e.getMessage());
        }
    }

    /**
     * 获取 Chat Assistant 详情
     *
     * GET /api/v1/ragflow/chats/{chatId}
     *
     * @param chatId Chat Assistant ID
     * @return Chat Assistant 详情
     */
    @GetMapping("/{chatId}")
    @PreAuthorize("hasAuthority('chat:read')")
    @Operation(summary = "获取 Chat Assistant 详情", description = "获取指定 Chat Assistant 的详细信息")
    public Result<ChatAssistantDetailVO> getChatAssistantDetail(@PathVariable String chatId) {
        try {
            log.info("收到获取 Chat Assistant 详情请求: chat_id={}", chatId);
            ChatAssistantDetailVO chat = ragFlowClient.getChatAssistantDetail(chatId);
            log.info("获取 Chat Assistant 详情成功: chat_id={}, name={}", chatId, chat.getName());
            return Result.success(chat);
        } catch (Exception e) {
            log.error("获取 Chat Assistant 详情失败: chat_id={}", chatId, e);
            return Result.error("获取 Chat Assistant 详情失败: " + e.getMessage());
        }
    }

    /**
     * 列出所有 Chat Assistant
     *
     * GET /api/v1/ragflow/chats
     *
     * @param page     页码（从1开始）
     * @param pageSize 每页大小
     * @return Chat Assistant 列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('chat:read')")
    @Operation(summary = "列出所有 Chat Assistant", description = "获取所有 Chat Assistant 列表，支持分页")
    public Result<List<ChatAssistantDetailVO>> listChatAssistants(
            @RequestParam(required = false) Integer page,
            @RequestParam(name = "page_size", required = false) Integer pageSize) {
        try {
            log.info("收到列出 Chat Assistant 请求: page={}, pageSize={}", page, pageSize);
            List<ChatAssistantDetailVO> chats = ragFlowClient.listChatAssistants(page, pageSize);
            log.info("列出 Chat Assistant 成功: count={}", chats.size());
            return Result.success(chats);
        } catch (Exception e) {
            log.error("列出 Chat Assistant 失败", e);
            return Result.error("列出 Chat Assistant 失败: " + e.getMessage());
        }
    }
}

